import web,datetime,hashlib
db=web.database(dbn='mysql',db='myblog',user='myblog')

def MD5(str):
	m=hashlib.md5()
	m.update(str)
	dest=m.hexdigest()
	return dest

def addUser(username,password):
	db.insert('admin',username=username,password=password)
	
def checkLogin(username,password):
	ident=db.select('admin',where='username=$username',vars=locals())
	if not ident:
		return False
	if ident[0]['password']==password:
		return True
	else:
		return False
	
def getPosts(isposted=None):
	if not isposted is None:
		posts=db.query('select post.*, postCateg.name from post inner join postCateg on post.categId=postCateg.id where isposted=$isposted',vars=locals())
	else:
		posts=db.query('select post.*, postCateg.name from post inner join postCateg on post.categId=postCateg.id')
	return posts
	
def getPost(id):
	post=db.select('post',where='id=$id',vars=locals())[0]
	return post
	
def updatePost(id,title,content,categId,isposted=0):
	db.update('post',where='id=$id',title=title,content=content,categId=categId,postTime=datetime.datetime.now(),isposted=isposted,vars=locals())
	
def getPostsCount(isposted=None):
	if isposted is None:
		queryStr='select count(*) totals from post'
	else:
		queryStr='select count(*) as totals from post where isposted='+str(isposted)
	count=db.query(queryStr)[0].totals
	return count
	
def addPost(title,content,categId,isposted):
	db.insert('post',title=title,content=content,categId=categId,postTime=datetime.datetime.now(),isposted=isposted)
		
	
def addCateg(categName,alias):
	db.insert('postCateg',name=categName,alias=alias)
	
def getCategs():
	categs=db.select('postCateg')
	return categs
	
def getCateg(id):
	return db.select('postCateg',where='id=$id',vars=locals())[0]

def updateCateg(id,name,alias):
	db.update('postCateg',where='id=$id',name=name,alias=alias,vars=locals())
	
def deleteCateg(ids):
	idStr=','.join(ids)
	whereStr='id in ('+idStr+')'
	db.delete('postCateg',where=whereStr)
	
		
		
	
